<template>
  <div class="PersonDetails">
    <div class="top">
      <h1>
        {{
          type === "view"
            ? "成员详情"
            : type === "edit"
            ? "编辑成员"
            : "新增成员"
        }}
      </h1>
      <div class="buttons">
        <el-button
          v-for="item in buttons[type]"
          :key="item.value"
          @click="
            item.value === 'save'
              ? save()
              : item.value === 'saveAdd'
              ? saveAdd()
              : $emit(item.value, personInfo)
          "
          size="small"
          >{{ item.label }}</el-button
        >
      </div>
    </div>
    <div class="content">
      <div class="view-content" v-if="type.includes('View')">
        <div
          v-for="(value, key) in infoMapping"
          :key="key"
          :class="'content-' + key"
        >
          <el-row v-for="item in value" :key="item.value">
            <el-col :span="4">
              <span>{{ item.label }}:</span>
            </el-col>
            <el-col :span="20">{{ getRealInfo(item) }}</el-col>
          </el-row>
        </div>
      </div>
      <div class="edit-content" v-else>
        <el-form
          :model="formData"
          ref="elForm"
          :rules="rules"
          label-width="80px"
        >
          <div class="edit-top">
            <el-form-item label="工号" prop="work_id">
              <el-input
                v-model="formData.work_id"
                placeholder="请输入工号"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="employee_name">
              <el-input
                v-model="formData.employee_name"
                placeholder="请填写姓名"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formData.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="账号" prop="employee_id">
              <template slot="label">
                <label>账号</label>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="成员的唯一标识、可以使用工号、邮箱等公司系统内统一的ID"
                  placement="top"
                >
                  <i class="el-icon-warning-outline"></i>
                </el-tooltip>
              </template>
              <el-input
                v-model="formData.employee_id"
                :disabled="type !== 'add'"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="默认密码"
              prop="login_password"
              v-if="ifshowPassword"
            >
              <el-input
                type="password"
                v-model="formData.login_password"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </div>
          <div class="edit-middle">
            <el-form-item label="座机" prop="line_number">
              <el-input
                v-model="formData.line_number"
                placeholder="请输入座机号码"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone_number">
              <el-input
                v-model="formData.phone_number"
                placeholder="仅支持大陆手机号"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="formData.email"
                placeholder="成员邮箱"
              ></el-input>
            </el-form-item>
          </div>
          <div class="edit-bottom">
            <el-form-item label="所属部门" prop="all_department">
              <div class="dept-row">
                <div class="depts" v-if="formData.all_department?.length">
                  <span
                    class="dept"
                    v-for="item in formData.all_department"
                    :key="item.dept_id"
                  >
                    <span
                      class="main-dept"
                      v-if="formData.main_dept_id === item.dept_id"
                      >{{ "主 | " }}</span
                    >
                    <span class="dept-name">{{ item.dept_name }}</span>
                    <i
                      class="el-icon-close"
                      @click="delDept('all_department', item.dept_id)"
                    ></i>
                  </span>
                </div>
                <el-input
                  v-else
                  disabled
                  placeholder="请添加所属部门"
                ></el-input>
                <tree-search
                  :dialogVisible="deptSelectVisible"
                  title="选择所属部门"
                  :main_dept="formData.main_dept_id"
                  :selected_dept="formData.all_department"
                  @changeDialogVisible="changeDialogVisible"
                  @dialogSubmit="dialogSubmit"
                >
                  <el-button
                    type="primary"
                    @click="deptSelectVisible = true"
                    slot="title"
                    plain
                    >添加</el-button
                  >
                </tree-search>
              </div>
            </el-form-item>
            <el-form-item label="负责部门" prop="responseDept">
              <div class="dept-row">
                <div class="depts" v-if="formData.responsible_dept?.length">
                  <span
                    class="dept"
                    v-for="item in formData.responsible_dept"
                    :key="item.dept_name"
                  >
                    <span class="dept-name">{{ item.dept_name }}</span>
                    <i
                      class="el-icon-close"
                      @click="delDept('responsible_dept', item.dept_id)"
                    ></i>
                  </span>
                </div>
                <el-input
                  v-else
                  disabled
                  placeholder="请添加负责部门"
                ></el-input>
                <tree-search
                  :dialogVisible="responseDeptSelectVisible"
                  title="选择负责部门"
                  :selected_dept="formData.responsible_dept"
                  @changeDialogVisible="changeDialogVisible1"
                  @dialogSubmit="dialogSubmit1"
                >
                  <el-button
                    type="primary"
                    @click="responseDeptSelectVisible = true"
                    slot="title"
                    plain
                    >添加</el-button
                  >
                </tree-search>
              </div>
            </el-form-item>
            <el-form-item label="直属上级" prop="leader_name">
              <person-search v-model="formData.leader_name" />
            </el-form-item>
            <el-form-item label="职务" prop="duty">
              <el-input
                v-model="formData.duty"
                placeholder="请输入职务"
                maxlength="50"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="排序" prop="order">
              <el-input
                maxlength="4"
                v-model="formData.order"
                placeholder="请输入0以上的数字"
              ></el-input>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import treeSearch from "../public/treeSearch.vue";
import personSearch from "../public/personSearch.vue";
import { addEmployee, getAllSettingsMap, updateEmployee } from "@/http/api";
export default {
  name: "PersonDetails",
  components: { treeSearch, personSearch },
  props: ["personInfo", "type"],
  data() {
    return {
      buttons: {
        normalView: [
          {
            label: "停用",
            value: "deactivate",
          },
          {
            label: "修改密码",
            value: "changePassword",
          },
          {
            label: "编辑",
            value: "edit",
          },
          {
            label: "返回",
            value: "back",
          },
        ],
        deactivateView: [
          {
            label: "恢复",
            value: "restore",
          },
          {
            label: "返回",
            value: "back",
          },
        ],
        edit: [
          {
            label: "保存",
            value: "save",
          },
          {
            label: "取消",
            value: "cancel",
          },
        ],
        add: [
          {
            label: "保存并继续添加",
            value: "saveAdd",
          },
          {
            label: "保存",
            value: "save",
          },
          {
            label: "取消",
            value: "cancel",
          },
        ],
      },
      infoMapping: {
        top: [
          {
            label: "工号",
            value: "work_id",
          },
          {
            label: "姓名",
            value: "employee_name",
          },
          {
            label: "性别",
            value: "sex",
          },
          {
            label: "账号",
            value: "employee_id",
          },
        ],
        middle: [
          {
            label: "座机",
            value: "line_number",
          },
          {
            label: "手机号",
            value: "phone_number",
          },
          {
            label: "邮箱",
            value: "email",
          },
        ],
        bottom: [
          {
            label: "所属部门",
            value: "all_department",
          },
          {
            label: "负责部门",
            value: "responsible_dept",
          },
          {
            label: "直属上级",
            value: "leader_name",
          },
          {
            label: "职务",
            value: "duty",
          },
          {
            label: "排序",
            value: "order",
          },
        ],
      },
      formData: {},
      rules: {
        employee_name: [{ required: true, message: "请填写姓名" }],
        employee_id: [{ required: true, message: "请填写账号" }],
        login_password: [
          {
            required: true,
            trigger: "blur",
            validator: (_, value, callback) => {
              if (value) {
                let ISPWD =
                  /^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])[0-9a-zA-Z]{8,20}/;
                if (ISPWD.test(value)) {
                  callback();
                } else {
                  callback(
                    new Error("密码要求8-20位, 必须包含英文大小写和数字")
                  );
                }
              } else {
                callback(new Error("请输入默认密码"));
              }
            },
          },
        ],
        all_department: [{ required: true, message: " " }],
        line_number: [
          { pattern: /^0\d{2,3}-?\d{7,8}$/, message: "请填写正确格式的座机号" },
        ],
        phone_number: [
          {
            required: true,
            trigger: "blur",
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: "请填写正确格式的手机号",
          },
        ],
        email: [
          {
            pattern:
              /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: "请填写正确格式的邮箱",
          },
        ],
        order: [
          {
            validator: (_, value, callback) => {
              if (!value) {
                callback();
              }
              if (
                isNaN(Number(value)) ||
                Number(value) < 0 ||
                Math.floor(Number(value)) !== Number(value)
              ) {
                callback(new Error("只能输入大于0的整数"));
              }
              callback();
            },
          },
        ],
      },
      deptSelectVisible: false,
      responseDeptSelectVisible: false,
      ifshowPassword: false,
      main_dept_hide: 0,
    };
  },
  async mounted() {
    let res = await getAllSettingsMap();
    if (res.code === 20041) {
      this.main_dept_hide = res.data.main_dept_hide;
    }
  },
  methods: {
    getRealInfo({ value: type }) {
      if (type === "sex") {
        return this.personInfo[type] ? "男" : "女";
      }
      if (type === "all_department" || type === "responsible_dept") {
        return (
          this.personInfo[type] &&
          this.personInfo[type]
            .reduce((res, cur) => {
              return res.concat(
                this.personInfo.main_dept_id === cur.dept_id
                  ? cur.dept_name +
                      (type === "all_department" && !this.main_dept_hide
                        ? "(主)"
                        : "")
                  : cur.dept_name +
                      (type === "all_department" && this.main_dept_hide
                        ? "(兼)"
                        : "")
              );
            }, [])
            .join("、")
        );
      }
      return this.personInfo[type];
    },
    changeToEdit(init_dept) {
      for (const key in this.infoMapping) {
        this.infoMapping[key].forEach((element) => {
          this.$set(
            this.formData,
            element.value,
            this.personInfo[element.value]
          );
        });
      }
      this.$set(this.formData, "main_dept_id", this.personInfo.main_dept_id);
      if (init_dept) {
        this.$set(this.formData, "main_dept_id", init_dept.dept_id);
        this.$set(this.formData, "all_department", [init_dept]);
        this.$set(this.formData, "login_password", "");
        this.ifshowPassword = true;
      }
    },
    delDept(type, id) {
      console.log(
        "%c Line:457 🥃🥃🥃 type",
        "color:#ffdd4d",
        type,
        this.formData
      );
      this.formData[type] = this.formData[type].filter((item) => {
        return item.dept_id !== id;
      });
    },
    changeDialogVisible(visible) {
      this.deptSelectVisible = visible;
    },
    changeDialogVisible1(visible) {
      this.responseDeptSelectVisible = visible;
    },
    dialogSubmit(depts, main_dept_id) {
      this.formData.all_department = depts;
      this.formData.main_dept_id = main_dept_id;
      this.deptSelectVisible = false;
    },
    dialogSubmit1(depts) {
      this.formData.responsible_dept = depts;
      this.responseDeptSelectVisible = false;
    },
    save() {
      if (
        !this.formData.all_department ||
        !this.formData.all_department.filter(
          (item) => item.dept_id === this.formData.main_dept_id
        ).length
      ) {
        this.$message({
          type: "warning",
          message: "请至少选择一个主部门",
        });
        return;
      }
      this.$refs.elForm.validate(async (res) => {
        if (res) {
          let data = { ...this.formData };
          data.leader_id = data.leader_name
            ? data.leader_name.employee_id
            : undefined;
          data.leader_name = data.leader_name
            ? data.leader_name.employee_name
            : undefined;
          data.order = parseInt(data.order);
          data.all_dept_id = data.all_department
            .map((item) => {
              return item.dept_id;
            })
            .join(",");
          data.responsible_dept_id = data.responsible_dept
            ? data.responsible_dept
                .map((item) => {
                  return item.dept_id;
                })
                .join(",")
            : undefined;
          data.department_name = data.all_department.filter((item) => {
            return item.dept_id === data.main_dept_id;
          })[0].dept_name;
          data.status = 1;
          let res = {};
          if (this.type !== "edit") {
            res = await addEmployee(data);
          } else {
            res = await updateEmployee(data);
          }
          if (res.code === 20011 || res.code === 20031) {
            this.$message.success(
              this.type !== "edit" ? "新增成功" : "修改成功"
            );
            this.$emit("cancel");
            this.$emit("refrushPersons");
          } else {
            this.$message({
              type: "error",
              message: res.msg,
            });
          }
        }
      });
    },
    saveAdd() {
      this.save();
    },
  },
};
</script>
<style lang="less" scoped>
.PersonDetails {
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    h1 {
      font-size: 16px;
      font-weight: normal;
    }
  }
  .content {
    margin-top: 10px;
    font-size: 14px;
    .view-content > div {
      border-bottom: 1px dashed #e8e8e8;
      padding: 10px 0;
      &:last-child {
        border-bottom: 0;
        padding-bottom: 0;
      }
      .el-row {
        padding: 10px 0;
        .el-col:first-child {
          color: #999;
        }
      }
    }
    .edit-content {
      margin: 20px;
      .el-form {
        & > div {
          border-bottom: 1px dashed #e8e8e8;
          padding: 10px 0;
        }
        .el-form-item {
          width: 80%;
          margin: 0 auto 22px;
          .el-icon-warning-outline {
            color: rgb(255, 152, 1);
            margin-left: 4px;
          }
          .depts .dept {
            display: inline-block;
            background-color: #eff0f1;
            color: #646a73;
            border: 1px solid #d9ecff;
            padding: 0 10px;
            margin-right: 4px;
            height: 28px;
            line-height: 26px;
            font-size: 14px;
            border-radius: 4px;
            .main-dept,
            i {
              color: #306eff;
            }
            i {
              cursor: pointer;
            }
          }
        }
      }
    }
  }
}
</style>
